package org.lee.netty.http;

import com.google.gson.Gson;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.StringUtil;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * DemoHttpServer
 *
 * @author dralee
 * @date 2022-01-03 21:20:40
 **/
public class DemoHttpServer {

    private int inetPort;

    public DemoHttpServer(int inetPort) {
        this.inetPort = inetPort;
    }

    public int getInetPort() {
        return inetPort;
    }

    public void init() throws Exception {

        EventLoopGroup parentGroup = new NioEventLoopGroup();
        EventLoopGroup childGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap server = new ServerBootstrap();
            // 1. 绑定两个线程组分别用来处理客户端通道的accept和读写时间
            server.group(parentGroup, childGroup)
                    // 2. 绑定服务端通道NioServerSocketChannel
                    .channel(NioServerSocketChannel.class)
                    // 3. 给读写事件的线程通道绑定handler去真正处理读写
                    // ChannelInitializer初始化通道SocketChannel
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 请求解码器
                            socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
                            // 将HTTP消息的多个部分合成一条完整的HTTP消息
                            socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));
                            // 响应转码器
                            socketChannel.pipeline().addLast("http-encoder", new HttpResponseEncoder());
                            // 解决大码流的问题，ChunkedWriteHandler：向客户端发送HTML5文件
                            socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                            // 自定义处理handler
                            socketChannel.pipeline().addLast("http-server", new NettyHttpServerHandler());
                        }
                    });
            // 4. 监听端口（服务器host和port端口），同步返回
            // ChannelFuture future = server.bind(inetHost, this.inetPort).sync();
            ChannelFuture future = server.bind(this.inetPort).sync();
            // 当通道关闭时继续向后执行，这是一个阻塞方法
            future.channel().closeFuture().sync();
        } finally {
            childGroup.shutdownGracefully();
            parentGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        DemoHttpServer server = new DemoHttpServer(8080);

        try {
            server.init();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("exception: " + e.getMessage());
        }
        System.out.println("server close!");

    }

    class NettyHttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
            System.out.println(fullHttpRequest);

            FullHttpResponse response = null;
            if (fullHttpRequest.method() == HttpMethod.GET) {
                System.out.println(getGetParamsFromChannel(fullHttpRequest));
                String data = "GET method over";
                ByteBuf buf = copiedBuffer(data, CharsetUtil.UTF_8);
                response = responseOk(HttpResponseStatus.OK, buf);
            } else if (fullHttpRequest.method() == HttpMethod.POST) {
                System.out.println(getPostParamsFromChannel(fullHttpRequest));
                String data = "POST method over";
                ByteBuf buf = copiedBuffer(data, CharsetUtil.UTF_8);
                response = responseOk(HttpResponseStatus.OK, buf);
            } else {
                response = responseOk(HttpResponseStatus.INTERNAL_SERVER_ERROR, null);
            }
            // 发送响应
            channelHandlerContext.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }

        private ByteBuf copiedBuffer(String data, Charset utf8) {
            return Unpooled.wrappedBuffer(data.getBytes());
        }

        private Map<String, Object> getPostParamsFromChannel(FullHttpRequest fullHttpRequest) {
            Map<String, Object> params = new HashMap<>();
            if (fullHttpRequest.method() == HttpMethod.POST) {
                // 处理post 请求
                String strContentType = fullHttpRequest.headers().get("Content-Type").trim();
                if (StringUtil.isNullOrEmpty(strContentType)) {
                    return null;
                }
                if (strContentType.contains("x-www-form-urlencoded")) {
                    params = getFormParams(fullHttpRequest);
                } else if (strContentType.contains("application/json")) {
                    params = getJSONParams(fullHttpRequest);
                } else {
                    return null;
                }
            }
            return params;
        }

        private Map<String, Object> getJSONParams(FullHttpRequest fullHttpRequest) {
            Map<String, Object> params = new HashMap<>();

            ByteBuf content = fullHttpRequest.content();
            byte[] reqContent = new byte[content.readableBytes()];
            content.readBytes(reqContent);
            String strContent = null;
            try {
                strContent = new String(reqContent, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            params = new Gson().fromJson(strContent, params.getClass());
//            JSONObject jsonParams = JSONObject.parseObject(strContent);
//            for (Object key : jsonParams.keySet()) {
//                params.put(key.toString(), jsonParams.get(key));
//            }

            return params;

        }

        private Map<String, Object> getFormParams(FullHttpRequest fullHttpRequest) {
            Map<String, Object> params = new HashMap<>();

            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), fullHttpRequest);
            List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();

            for (InterfaceHttpData data : postData) {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    MemoryAttribute attribute = (MemoryAttribute) data;
                    params.put(attribute.getName(), attribute.getValue());
                }
            }

            return params;
        }

        private FullHttpResponse responseOk(HttpResponseStatus status, ByteBuf buf) {
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    status, buf);
            if (buf != null) {
                response.headers().set("Content-Type", "text/plain;charset=UTF-8");
                response.headers().set("Content-Length", response.content().readableBytes());
            }
            return response;
        }

        private Map<String, Object> getGetParamsFromChannel(FullHttpRequest fullHttpRequest) {
            Map<String, Object> params = new HashMap<>();
            if (fullHttpRequest.method() == HttpMethod.GET) {
                QueryStringDecoder decoder = new QueryStringDecoder(fullHttpRequest.uri());
                Map<String, List<String>> paramList = decoder.parameters();

                for (Map.Entry<String, List<String>> entry : paramList.entrySet()) {
                    params.put(entry.getKey(), entry.getValue().get(0));
                }
                return params;
            }
            return params;
        }

    }
}